https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value

It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples.


In [8]:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
#itemgetter(0) if you want sort by key
sorted_x = sorted(x.items(), key=operator.itemgetter(1),reverse=True) 
for k,v in sorted_x:
    print(k,v)


3 4
4 3
1 2
2 1
0 0

In [14]:
print(sorted_x)
print(type(sorted_x))
print(type(sorted_x[0]))


[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
<class 'list'>
<class 'tuple'>

Other Approach


In [2]:
#Less efficient
mydict = {'a':1,'b':3,'c':2}
sorted(mydict.items(), key=lambda x: x[1])


Out[2]:
[('a', 1), ('c', 2), ('b', 3)]

In [10]:
#Less efficient
mydict = {'a':1,'b':3,'c':2}
sorted(mydict, key=mydict.get)


Out[10]:
['a', 'c', 'b']

In [14]:
for w in sorted(mydict, key=mydict.get, reverse=True):
  print(w, mydict[w])


b 3
c 2
a 1

In [11]:
sorted(mydict, key=lambda key: mydict[key])


Out[11]:
['a', 'c', 'b']

In [2]:
mydict = {'a':1,'b':3,'c':2}
sorted(mydict, key=lambda key: mydict[key],reverse=True)


Out[2]:
['b', 'c', 'a']

In [6]:
mydict = {'a':1,'b':3,'c':2}
sorted_dict=sorted(mydict, key=lambda key: mydict[key],reverse=True)
for i in sorted_dict:
    print(i,mydict[i])


b 3
c 2
a 1